<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>socket聊天室</title>
    <style>
        *{
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body{
            font: 14px Helvetica,Arial;
        }
        form{
            background: #000;
            padding: 3px;
            position: fixed;
            bottom: 0;
            width: 100%;
        }
        form input {
            border: 0;
            padding: 10px;
            width: 90%;
            margin-right: 1%;
        }
        form button{
            width: 8%;
            background: rgb(130,224,255);
            border: none;
            padding: 10px;
        }
        #messages{
            list-style-type: none;
            margin: 0;
            padding: 0;
        }
        #messages li{
            padding: 5px 10px;
        }
        #message li:nth-child(odd){
            background: #eee;
        }

    </style>
</head>
<body>
    <ul id="messages">
        <form action="">
            <input autocomplete="off" id="m">
            <button id="btn">send</button>
        </form>
    </ul>
</body>
</html>
<script src="./socket.io.js"></script>
<script>
    // 链接socket.oi服务器
    const socket = io("ws://localhost:3001")
    let $ =(id)=>document.getElementById(id)
    let btn = $("btn")
    let input = $("m")
    let message = $("messages")

    btn.onclick=function(e){
        e.preventDefault()
        if (input.value=="") return
        let msg = input.value//获取输入框里的值
        socket.emit("onChat",msg)
    }
    socket.on("showChat",msg=>{
        let li = document.createElement("li");
        li.innerHTML = msg
        message.appendChild(li)
        input.value =""
        document.documentElement.scrollTop = document.body.scrollHeight
    })
    </script>